//
//  HZOrderConfirmViewController.m
//  app
//
//  Created by 刘华舟 on 15/5/6.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HZOrderConfirmViewController.h"
#import "SNExpressHabitViewController.h"
#import "SNOrderFormDetailViewController.h"
#import "HZOrderMessageFooterView.h"
#import "HZOrderBuyerPayWayViewController.h"
#import "HZAddressDetailSelectViewController.h"

//view
#import "HZTableView.h"
#import "HZOrderConfirmHeaderView.h"
#import "HZOrderConfirmAddressHeaderView.h"
#import "HZDispichSelectHeaderView.h"
#import "HZOrderPayWayHeaderView.h"

#import "HZOrderCellGoods.h"

#import "HZOrderGoodsEmptyView.h"
#import "HZProductGiftListView.h"


//model
#import "HZRemoteResult.h"
#import "HZOrderConfirmVCModel.h"
#import "HZOrderByerAddressModel.h"


//tools
#import "HZMallCartsHttpManager.h"
#import "HZBase64Handler.h"
#import "HZMallSqlDataManager.h"

//category
#import "UIAlertView+Conveniently.h"
#import "MBProgressHUD+Conveniently.h"

static const NSInteger kOrderSaleoutAlertTag = 3001;

static const NSInteger kOrderSubmitAlertTagFailt = 4001;
static const NSInteger kOrderReadyToSubmitAlertTag = 4002;
static const NSInteger kOrderToMuchShopAlertTag = 4003;

@interface HZOrderConfirmViewController()<UITextFieldDelegate,UITextViewDelegate,UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate,HZOrderBuyerPayWayDelegate>

@property (strong, nonatomic) HZTableView *tableView;



@property (strong, nonatomic) HZOrderConfirmAddressHeaderView* addressHeaderView;
@property (strong, nonatomic) HZDispichSelectHeaderView* dispichWayView; //配送方式选择视图
@property (strong, nonatomic) HZOrderPayWayHeaderView* payWayView;//付款方式选择

@property (strong, nonatomic) HZOrderMessageFooterView* msgHeaderView;

@property (strong, nonatomic) HZOrderConfirmHeaderView *confirmPanel;


@property (strong, nonatomic) UIButton *submitBtn;
@property (strong, nonatomic) HZOrderGoodsEmptyView *emptyView;

@property (strong, nonatomic) NSString *paramStr;

@property (strong, nonatomic) HZRemoteResult *confirmOrderResult;
@property (strong, nonatomic) HZRemoteResult *createOrderResult;

@property (strong, nonatomic) HZOrderConfirmVCModel *data;

@property (strong, nonatomic) NSDictionary *submitDict;

@property (nonatomic, assign) BOOL textViewInput;
@property (nonatomic, assign) BOOL textFieldInput;

@end

@implementation HZOrderConfirmViewController

- (instancetype)initWithParams:(NSString *)paramStr{
    if (self = [super init]) {
        if (paramStr) {
            self.paramStr = paramStr;
        }else{
            self.paramStr = @"[]";
        }
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"订单确认";
    
    UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithTitle:self.title style:UIBarButtonItemStylePlain target:nil action:nil];
    UIImage* image = [UIImage imageNamed:@"ic_actionbar_home_up"];
    [back setBackButtonBackgroundImage:[image resizableImageWithCapInsets:UIEdgeInsetsMake(0, image.size.width, 0, 0)] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [back setBackButtonTitlePositionAdjustment:UIOffsetMake(2, 0) forBarMetrics:UIBarMetricsDefault];
    
    
    //关闭自动适应UIScrollView
    self.navigationController.navigationBar.hidden = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.view.backgroundColor = HZ_MALL_M_LIGHT_GRAY_BACKGROUND_COLOR;
    
    //添加tableView
    self.tableView = [[HZTableView alloc] initWithFrame:CGRectOf([self.view.ufo fx:UB_LEFT fy:UB_TOP oy:self.navigationAndStatusBarHeight],
                                                                 [self.view.ubo fw:UB_WIDTH fh:UB_HEIGHT oh:-kOrderConfirmHeaderViewHeight-self.navigationAndStatusBarHeight]) style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = HZ_CLEAR_COLOR;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.nothingRefreshView = [[UIRefreshNotingRefreshView alloc] initWithView:self.tableView viewController:self tryAgain:@selector(loadOrderData)];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    self.tableView.hidden = YES;
    

    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectOf([self.ubo fx:UB_LEFT fy:UB_TOP], [self.ubo fw:UB_WIDTH oh:0.1f])];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectOf([self.ubo fx:UB_LEFT fy:UB_TOP], [self.ubo fw:UB_WIDTH oh:0.1f])];
    
    
    
    //初始化商品个数按钮
    self.confirmPanel = [[HZOrderConfirmHeaderView alloc] initWithFrame:CGRectOf([self.ubo fx:UB_LEFT fy:UB_BOTTOM oy:-kOrderConfirmHeaderViewHeight],
                                                              [self.ubo fw:UB_WIDTH oh:kOrderConfirmHeaderViewHeight])];
    self.confirmPanel.backgroundColor = HZ_WHITE_COLOR;
    [self.view addSubview:self.confirmPanel];
    self.confirmPanel.targetCallerConfirm = [UBTargetCaller of:self action:@selector(submitBtnOnClick)];
    self.confirmPanel.hidden = YES;
    
    /** 地址选择 -write by khzliu */
    self.addressHeaderView = [[HZOrderConfirmAddressHeaderView alloc] initWithFrame:CGRectZero];
    self.addressHeaderView.nameValueLabel.delegate = self.addressHeaderView.addressValueLabel.delegate = self.addressHeaderView.phoneValueLabel.delegate = self;
    self.addressHeaderView.targetCallerRoom = [UBTargetCaller of:self action:@selector(changeAddressRoom:)];
    /** 配送方式选择 -write by khzliu */
    self.dispichWayView = [[HZDispichSelectHeaderView alloc] initWithFrame:CGRectZero];
    /** 付款方式选择 -write by khzliu */
    self.payWayView = [[HZOrderPayWayHeaderView alloc] initWithFrame:CGRectZero];
    self.payWayView.targetCallerPayWay = [UBTargetCaller of:self action:@selector(payWayViewOnClick)];
    
    self.msgHeaderView = [[HZOrderMessageFooterView alloc] initWithFrame:CGRectZero];
    self.msgHeaderView.msgTextView.delegate = self;
    
    self.emptyView = [[HZOrderGoodsEmptyView alloc] initWithFrame:self.view.frame];
    self.emptyView.backgroundColor = HZ_WHITE_COLOR;
    [self.emptyView setHidden:YES];
    [self.view addSubview:self.emptyView];
    
    self.confirmOrderResult = [HZRemoteResult target:self action:@selector(confirmOrderFinishLoadData:)];
    self.createOrderResult = [HZRemoteResult target:self action:@selector(createOrderFinishLoadData:)];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    
    self.submitDict = @{};

    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = NO;
    
    if (self.data == nil) {
        if ([self checkUserLongin]) {
            //刚进来进行数据加载
            [self.tableView.nothingRefreshView showLoadingMsg:@"卖命加载中.." errorMsg:@"订单拉取失败，点击重试"];
            //刚进来进行数据加载
            [self loadOrderData];
        }
    }
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark 加载订单数据
- (void)loadOrderData{
    if (self.data == nil) {
        HZMallCartsHttpManager *httpManager = [HZMallCartsHttpManager shareHttpRequestMananger];
        NSString *cmid = [[NSUserDefaults standardUserDefaults] stringForKey:kMyAreaID];
        if (cmid == nil || cmid.length < 1) {
            cmid = @"0";
        }
        NSDictionary *params = @{APIKEY_mall_order_form:self.paramStr,APIKEY_mall_cmid:cmid};
        [httpManager loadOrderConfirmDataWithParams:params result:self.confirmOrderResult];
    }else{
        [self.tableView reloadData];
    }
    
}

#pragma mark 提交订单
- (void)submitBtnOnClick{
    
    if (self.data) {
        
        if (self.data.cmid.length < 1 || [self.data.cmid isEqualToString:@"0"]) {
            [MyToast showDefaultBottonWithText:@"您未设置默认小区，请在个人中心设置默认小区"];
            
            [self.navigationController popViewControllerAnimated:YES];
            return;
        }
        
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        
        //地址房间号
        if (self.data.addressModel.groupID && self.data.addressModel.groupID.length > 0) {
            if (self.data.addressModel.roomID && self.data.addressModel.roomID.length > 0) {
                [params setObject:self.data.addressModel.roomID forKey:@"houseid"];
            }else{
                [MyToast showDefaultBottonWithText:@"请选择房屋"];
                return;
            }
        }else{
            [params setObject:self.data.houseid forKey:@"houseid"];
        }
        
        /** cmid -write by khzliu */
        
        [params setObject:self.data.cmid forKey:APIKEY_mall_cmid];
        
        /** 配送方式 -write by khzliu */
        
        if (self.dispichWayView.isPickup) {
            [params setObject:@"1" forKey:@"cpucbt"];
        }else{
            [params setObject:@"0" forKey:@"cpucbt"];
        }
        
        [params setObject:self.data.orderHeaderModel.checkMoney forKey:APIKEY_mall_money];
        
        if (self.data.orderHeaderModel.useGoldBeans) {
            [params setObject:self.data.orderHeaderModel.avalibleGoldBeansNum forKey:APIKEY_mall_usedGold];
        }
        
        [params setObject:self.data.addressModel.nation forKey:APIKEY_mall_nation];
        [params setObject:self.data.addressModel.province forKey:APIKEY_mall_province];
        

        [params setObject:self.data.addressModel.city forKey:APIKEY_mall_city];
        [params setObject:self.data.addressModel.district forKey:APIKEY_mall_district];
        
        if (self.data.addressModel.fullAddress == nil || self.data.addressModel.fullAddress.length <= 0) {
            [UIAlertView alertWithTitle:@"" message:@"请您填写收货人的详细地址"];
            return;
        }
        [params setObject:self.data.addressModel.fullAddress forKey:APIKEY_mall_address];
        
        
        [params setObject:self.data.postage forKey:APIKEY_mall_postcode];
        
        if (self.data.addressModel.phone == nil || self.data.addressModel.phone.length <= 0) {
            [UIAlertView alertWithTitle:@"" message:@"请您填写收货人电话号码"];
            return;
        }
        [params setObject:self.data.addressModel.phone forKey:APIKEY_mall_phone];
        
        if (self.data.addressModel.receiver == nil || self.data.addressModel.receiver.length <= 0) {
            [UIAlertView alertWithTitle:@"" message:@"请您填写收货人名称"];
            return;
        }
        [params setObject:self.data.addressModel.receiver forKey:APIKEY_mall_receiver];
        
        if (self.data.isNeedBill) {
            [params setObject:@"1" forKey:APIKEY_mall_invoice];
            [params setObject:self.data.billTitle forKey:APIKEY_mall_invoice_name];
            [params setObject:self.data.billTypeType forKey:APIKEY_mall_invoice_type];
        }else{
            [params setObject:@"0" forKey:APIKEY_mall_invoice];
        }
        
        [params setObject:self.data.dispatchType forKey:APIKEY_mall_express_habit];
        
        //付款方式
        [params setObject:self.data.payTypeNum forKey:APIKEY_mall_payType];
        
        if (self.msgHeaderView.msgTextView.text.length > 0 && ![self.msgHeaderView.msgTextView.text isEqualToString:@"给卖家留言"]) {
            [params setObject:self.msgHeaderView.msgTextView.text forKey:APIKEY_mall_notes];
        }
        
        [params setObject:self.data.postage forKey:APIKEY_mall_express_fee];
        
        NSMutableArray *goodsToBuyArray = [NSMutableArray array];
        for (HZOrderCellModel *model in self.data.goodsArray) {
            NSMutableDictionary *goods = [NSMutableDictionary dictionary];
            [goods setObject:model.actID forKey:APIKEY_mall_act_id];
            [goods setObject:model.shopID forKey:APIKEY_mall_shop_id];
            [goods setObject:model.productID forKey:APIKEY_mall_product_id];
            [goods setObject:model.productNum forKey:APIKEY_mall_num];
            [goods setObject:model.salePrice forKey:APIKEY_mall_price];
            [goods setObject:model.giftModel.product_id?model.giftModel.product_id:@"" forKey:APIKEY_mall_gifts];
            
            
            [goodsToBuyArray addObject:[goods JSONString]];
        }
        
        NSString *paramsStr = [NSString stringWithFormat:@"[%@]", [goodsToBuyArray componentsJoinedByString:@","]];
        
        [params setObject:[HZBase64Handler encodeBase64WithString:paramsStr] forKey:APIKEY_mall_products];
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"确认提交订单" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        alertView.tag = kOrderReadyToSubmitAlertTag;
        
        self.submitDict = params;
        
        [alertView show];
        
    }
}

#pragma mark 拉取订单数据完成
- (void)confirmOrderFinishLoadData:(HZRemoteResult *)remote{
    
    if (remote.response.status == JKResponseServerError || remote.response.status == JKResponseLocalError) {
        self.tableView.hidden = NO;
        [self.tableView.nothingRefreshView activeStop];
        [self.emptyView hide];
        
        self.confirmPanel.hidden = YES;
    }else if (remote.response.status == JKResponseOK) {
        [self.tableView.nothingRefreshView remove];
        self.tableView.hidden = NO;
        
        self.data = (HZOrderConfirmVCModel *)remote.info;
        
        
        if (self.data) {
            
            /** 填充收货人信息 -write by khzliu */
            [self.addressHeaderView displayViewWithModel:self.data.addressModel];
            
            /** 打开选择自提模式 -write by khzliu */
            if (self.data.storehouse.length) {
                [self.dispichWayView showPickupMessage:self.data.storehouse];
            }
            
            /** 填充支付方式 -write by khzliu */
            [self.payWayView changePayWayWithMessage:self.data.payTypeName netPay:[self.data.payTypeNum boolValue]];
            
            /** 打开计价面板 -write by khzliu */
            self.confirmPanel.hidden = NO;
            
            [self.confirmPanel refreshCountPanelWithNum:[NSString stringWithFormat:@"%d", self.data.goodsArray.count] postage:self.data.postage money:self.data.totalPrices];
        }
        [self.tableView reloadData];
        
        
        [self.emptyView hide];
    }else{
        [self.tableView.nothingRefreshView remove];
        self.tableView.hidden = NO;
        self.confirmPanel.hidden = YES;
        
        [self.emptyView hide];
        
        [self.tableView reloadData];
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:remote.response.message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alertView.tag = kOrderSaleoutAlertTag;
        [alertView show];
    }
    
//    if (self.data && [self.data.splitOrders integerValue] <= 0) {
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"本订单含有多个供应商，请重新分别下单" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        alertView.tag = kOrderToMuchShopAlertTag;
//        [alertView show];
//    }
}

#pragma mark 提交订单数据完成
- (void)createOrderFinishLoadData:(HZRemoteResult *)remote{
    
    if (remote.response.status == JKResponseOK) {
        
        //如果订单生产成功则清空购物车，并刷新购物车数据
        [self deleteCartListGoods];
        
        HZMallSqlDataManager *sqlDataManager = [HZMallSqlDataManager defaultManager];
        
        //删除购买的表中的标记
        for (HZOrderCellModel *model in self.data.goodsArray) {
            [sqlDataManager updateProductChoseStatuWithProductID:model.productID selected:NO];
        }
        
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationCartsRefresh object:nil];
        
        SNOrderFormDetailViewController *orderFormDtVC = [[SNOrderFormDetailViewController alloc] init];
        
        orderFormDtVC.sn = [self.createOrderResult.info stringForKey:@"sn" nilValue:@"0"];
        orderFormDtVC.popToVCNameStr = @"HZOrderConfirmViewController";
        [self.navigationController pushViewController:orderFormDtVC animated:YES];
        
    }else{
        if (remote.response.message.length > 0) {
            [UIAlertView showAlertWithTitle:@"提交失败" message:remote.response.message delegate:self tag:kOrderSubmitAlertTagFailt];
        }else{
            [UIAlertView showAlertWithTitle:@"提交失败" message:kMallReminderOrderCommitFailed delegate:self tag:kOrderSubmitAlertTagFailt];
        }
        
        
    }
    
}


//检查用户是否登录
- (BOOL)checkUserLongin{
    NSString *uid = [[NSUserDefaults standardUserDefaults] stringForKey:@"uid"];
    if (uid && uid.length>0) {
        return YES;
    }
    return NO;
}



#pragma mark 修改地址建筑
- (void)changeAddressRoom:(NSString *)sign{
    
    if (self.data.cmid && ![self.data.cmid isEqualToString:@"-1"]) {
        HZAddressDetailSelectViewController *selectVC = [[HZAddressDetailSelectViewController alloc] init];
        
        selectVC.sign = sign;
        if ([sign isEqualToString:@"1"]) {
            selectVC.cmid = self.data.cmid;
        }else if([sign isEqualToString:@"2"]){
            selectVC.cmid = self.data.addressModel.groupID;
        }else if([sign isEqualToString:@"3"]){
            selectVC.cmid = self.data.addressModel.buildingID;
        }

        selectVC.model = self.data.addressModel;
        
        selectVC.targetCallerAddressChange = [UBTargetCaller of:self action:@selector(finishChangedAddress:)];
        
        [self.navigationController pushViewController:selectVC animated:YES];
    }
}

#pragma mark 完成修改地址信息
- (void)finishChangedAddress:(HZOrderByerAddressModel *)model{
    
    self.data.addressModel = model;
    
    [self.addressHeaderView displayViewWithModel:model];
}

#pragma mark 点击修改配送方式
- (void)payWayViewOnClick{
    HZOrderBuyerPayWayViewController *byrVC = [[HZOrderBuyerPayWayViewController alloc] init];
    byrVC.delegate = self;
    byrVC.data = self.data;
    [self.navigationController pushViewController:byrVC animated:YES];
}

#pragma mark HZOrderBuyerPayWayDelegate 修改配送方式
- (void)finishOrderBuyerPayWaySetting{
    
    /** 填充支付方式 -write by khzliu */
    [self.payWayView changePayWayWithMessage:self.data.payTypeName netPay:[self.data.payTypeNum boolValue]];

    [self.tableView reloadData];
    
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    self.textFieldInput = YES;
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    self.textFieldInput = NO;
    return YES;
}

- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    self.textViewInput = YES;
    return YES;
}

- (BOOL)textViewShouldEndEditing:(UITextView *)textView
{
    self.textViewInput = NO;
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (textField.tag == 2000) {
        self.data.addressModel.receiver = textField.text;
    }
    
    if (textField.tag == 2001) {
        self.data.addressModel.phone = textField.text;
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([string isEqualToString:@"\n"]) {
        [textField resignFirstResponder];
        return NO;
    }
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.addressHeaderView.nameValueLabel resignFirstResponder];
    [self.addressHeaderView.phoneValueLabel resignFirstResponder];
    return YES;
}

#pragma mark 键盘事件
- (void)keyboardWillShow:(NSNotification *)noti{
    
    CGRect rect = [[noti.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    CGFloat y = 0;
    if (rect.size.height > 100) {
        y = rect.size.height;
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, y - kOrderConfirmHeaderViewHeight, 0);
    }
    
    if (self.textViewInput) {
        
        CGFloat contentOffsetY;
        if (self.view.frame.size.height < 500) {
            contentOffsetY = self.tableView.contentSize.height - y + kOrderConfirmHeaderViewHeight + 20;
        } else if (self.view.frame.size.height < 570 && self.view.frame.size.height > 500) {
            contentOffsetY = self.tableView.contentSize.height - y - kOrderConfirmHeaderViewHeight + 10;
        } else {
            contentOffsetY = self.tableView.contentSize.height - y - kOrderConfirmHeaderViewHeight - 50;
        }
        
        self.tableView.contentOffset = CGPointMake(0, contentOffsetY);
    
    } else if (self.textFieldInput) {
        if (self.view.frame.size.height < 500) { //480
            
            self.tableView.contentOffset = CGPointMake(0, self.tableView.contentSize.height - self.tableView.frame.size.height);
        }
    }
}

-(void)keyboardWillHide:(NSNotification *)noti{
    
    if (self.textViewInput) {
        return;
    }
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.25];

    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    if (self.view.frame.size.height < 570) {
        self.tableView.contentOffset = CGPointMake(0, self.tableView.contentSize.height - self.tableView.frame.size.height);
    } else {
        self.tableView.contentOffset = CGPointMake(0, 0);
    }

    [UIView commitAnimations];
    
}
#pragma mark UITableViewDelegate UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return self.data.goodsArray.count;
    }else{
        return 0;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if(self.data){
        return 5;
    }else{
        return 0;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HZOrderCellModel *model = nil;
    
    NSInteger row = indexPath.row;
    
    if (indexPath.section == 0) {
        model = [self.data.goodsArray objectAtIndex:row];
        
        HZOrderTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:[HZOrderCellModel reuseIdentifierOfType:model.orderCellType]];
        HZOrderCellGoods *goodsCell = [HZOrderCellGoods cellWithTableView:self.tableView];
        cell = goodsCell;
        
        [cell displayCell:model showLine:NO];
        
        return cell;
        
    }else{
        UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"];
        return cell;
    }
  
        
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        HZOrderCellModel *model  = [self.data.goodsArray objectAtIndex:indexPath.row];
        return model.cellHeight;
    }else{
        return 0;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 10.0f;
    }else if(section == 1){
        return HZOrderConfirmAddressHeaderViewHeight;
    }else if(section == 2){
        if (self.data.storehouse.length) {
            return kHZDispichSelectHeaderItemHeight*2;
        }else{
            return kHZDispichSelectHeaderItemHeight;
        }
    }else if(section == 3){
        return kHZOrderPayWayHeaderViewHeight;
    }else if(section == 4){
        return kHZOrderMessageFooterViewHeight;
    }else{
        return 0.1f;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section >4) {
        return 0.1f;
    }else{
        return 10.0f;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return self.addressHeaderView;
    }else if (section == 2){
        return self.dispichWayView;
    }else if(section == 3){
        return self.payWayView;
    }else if(section == 4){
        return self.msgHeaderView;
    }else{
        return nil;
    }
}

- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 2) {
        return NO;
    }
    return YES;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
    
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    switch (alertView.tag) {
        case kOrderSubmitAlertTagFailt:
            [self.navigationController popViewControllerAnimated:YES];
            break;
        case kOrderReadyToSubmitAlertTag:
        {
            if (buttonIndex == 0) {
                
                HZMallCartsHttpManager *httpManager = [HZMallCartsHttpManager shareHttpRequestMananger];
                
                [httpManager createOrderDataWithParams:self.submitDict result:self.createOrderResult];

            }
        }
            break;
        case kOrderToMuchShopAlertTag:
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
            break;
        case kOrderSaleoutAlertTag:
        {
            [self.navigationController popViewControllerAnimated:YES];
        }
            break;
    }
}

//清空已经下单的购物车内的商品
- (void)deleteCartListGoods
{
    
    if (!(self.data && self.data.goodsArray.count > 0)) {
        return;
    }
    
    NSMutableArray *goodsToBuyArray = [NSMutableArray array];
    for (HZOrderCellModel *model in self.data.goodsArray) {
        NSMutableDictionary *goods = [NSMutableDictionary dictionary];
        [goods setObject:model.actID forKey:APIKEY_mall_act_id];
        [goods setObject:model.shopID forKey:APIKEY_mall_shop_id];
        [goods setObject:model.productID forKey:APIKEY_mall_product_id];
        [goods setObject:model.productNum forKey:APIKEY_mall_num];
        [goods setObject:model.salePrice forKey:APIKEY_mall_price];
        [goods setObject:model.giftModel.product_id?model.giftModel.product_id:@"" forKey:APIKEY_mall_gifts];
        
        
        [goodsToBuyArray addObject:[goods JSONString]];
    }
    
    NSString *paramsStr = [NSString stringWithFormat:@"[%@]", [goodsToBuyArray componentsJoinedByString:@","]];
    
    
    NSDictionary *params = @{APIKEY_mall_goods:[HZBase64Handler encodeBase64WithString:paramsStr]};
    
    HZMallCartsHttpManager *httpManager = [HZMallCartsHttpManager shareHttpRequestMananger];
    
    [httpManager deleteGoodsWithParams:params result:nil];
}

@end
